package com.jmes.web.view;

import com.jmes.web.filter.AuthFilter;
import com.jmes.web.model.User;
import com.jmes.web.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import javax.servlet.http.HttpSession;

/**
 * 登陆控制类.
 * User: jinshunlong
 * Date: 13-4-13
 * Time: 下午10:12
 */
public class LoginComposer implements Composer {
    private static Logger logger = Logger.getLogger(LoginComposer.class);
    /**
     * Invokes after ZK loader creates this component,
     * initializes it and composes all its children, if any.
     *
     * @param comp the component has been composed
     */
    @Override
    public void doAfterCompose(Component comp) throws Exception {
        final Window window = (Window)comp;
        Button button = (Button)window.getFellow("submit");
        button.addEventListener("onClick",new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                Textbox textbox = (Textbox)window.getFellow("userName");
                String userName = textbox.getValue();
                Textbox pwdTextBox = (Textbox)window.getFellow("pwd");
                String pwd = pwdTextBox.getValue();
                if(StringUtils.isBlank(userName) || StringUtils.isBlank(pwd)){
                    Messagebox.show("请输入账号和密码");
                    return;
                }
                userName = userName.trim();
                User user = UserService.getUserByName(userName);
                logger.info("===" + userName + "====");

                if(user == null){
                    Messagebox.show("账号不存在");
                    return;
                }
                logger.info(user.getId());
                if(pwd.equals(user.getPwd())){
                    AuthFilter.login(user,(HttpSession)window.getDesktop().getSession().getNativeSession());
                    Executions.sendRedirect("/home.zul");
                }else {
                    Messagebox.show("密码错误");
                    return;
                }
            }
        });
    }
}
